#pragma once
#include<Arduino.h>
#include<ESP8266WiFi.h>

namespace ganix {
    namespace wifi {
        void wifi_connect(const String &ssid, const String &passwd) {
            Serial.printf("start connect to %s\n", ssid.c_str());
            WiFi.mode(WIFI_STA);
            WiFi.begin(ssid, passwd);
            while (WiFi.status() != WL_CONNECTED) {
                Serial.printf("connect not ready yet (status: %d), waiting...\n", WiFi.status());
                delay(500);
            }
            Serial.printf("connected, IP: (%s)\n", WiFi.localIP().toString().c_str());
        }

        void wifi_ap(IPAddress ip, IPAddress gateway, IPAddress subnet, String ap_name, String passwd) {
             Serial.printf("starting up ap: %s\n", ap_name.c_str());
             WiFi.mode(WIFI_AP);
             WiFi.softAPConfig(ip, gateway, subnet);
             WiFi.softAP(ap_name, passwd);
             Serial.printf("started ap: %s, ip is : ", ap_name.c_str());
             Serial.println(WiFi.softAPIP());
        }

        void wifi_ap(String ap_name, String passwd) {
            wifi_ap(
                IPAddress(192,168,66,1),
                IPAddress(192,168,66,1),
                IPAddress(255,255,255,0),
                ap_name, passwd
            );
        }
        
        String get_mac() {
            uint8_t mac[6];
            WiFi.macAddress(mac);
            String mac_str = "";
            for (int i=0; i<6; i++) {
                char buf[5];
                sprintf(buf, "%02x", mac[i]);
                mac_str += buf;
                if (i < 5) {
                    mac_str += ':';
                }
            }
            return mac_str;
        }

        int get_conn() {
            return WiFi.softAPgetStationNum();
        }
    } // namespace wifi
}